package com.marktotop.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.PageList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.marktotop.converter.DepartmentConverter;
import com.marktotop.entity.system.*;
import com.marktotop.enums.BizUserTypeEnum;
import com.marktotop.enums.UserStatusEnum;
import com.marktotop.enums.UserTypeEnum;
import com.marktotop.error.SystemCodeEnum;
import com.marktotop.error.SystemException;
import com.marktotop.mapper.DepartmentMapper;
import com.marktotop.mapper.RoleMapper;
import com.marktotop.mapper.UserMapper;
import com.marktotop.mapper.UserRoleMapper;
import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.vo.system.DeanVO;
import com.marktotop.vo.system.DepartmentVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-07-12
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public DepartmentVO editDept(Long departmentId) throws SystemException {
        Department department = departmentMapper.selectById(departmentId);
        if(department == null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"所编辑的部门不存在，请查证...");
        }
        return DepartmentConverter.converterToDepartmentVO(department);
    }

    /**
     * 条件分页展示部门信息
     *
     * @param pageNum
     * @param pageSize
     * @param departmentVO
     * @return
     */
    @Override
    public ResultBean findDepartmentList(Integer pageNum, Integer pageSize, DepartmentVO departmentVO) {
        PageHelper.startPage(pageNum, pageSize);
        List<Department> departments = departmentMapper.selectList(
                        new QueryWrapper<Department>()
                        .like(StringUtils.isNotBlank(departmentVO.getName()),"name",departmentVO.getName()));
        //转vo
        List<DepartmentVO> departmentVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(departments)) {
            for (Department department : departments) {
                DepartmentVO d = new DepartmentVO();
                BeanUtils.copyProperties(department, d);
                d.setTotal(userMapper.selectCount(new QueryWrapper<User>()
                             .eq("department_id",department.getId())
                             .ne("type",UserTypeEnum.SYSTEM_ADMIN.getTypeCode())));
                departmentVOS.add(d);
            }
        }
        // 开启分页
        PageInfo<Department> info = new PageInfo<>(departments);
        return ResultBean.ok().message("获取全部部门信息成功!")
                .data("depts",departmentVOS)
                .data("total",info.getTotal());
    }


    /**
     * 查询所有部门
     *
     * @return
     */
    @Override
    public List<DepartmentVO> findAllVO() {
        List<Department> departments = departmentMapper.selectList(null);
        // 转vo
        List<DepartmentVO> departmentVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(departments)) {
            for (Department department : departments) {
                DepartmentVO d = new DepartmentVO();
                BeanUtils.copyProperties(department, d);
                d.setTotal(userMapper.selectCount(new QueryWrapper<User>()
                        .eq("department_id",department.getId())
                        .ne("type",UserTypeEnum.SYSTEM_ADMIN.getTypeCode())));
                departmentVOS.add(d);
            }
        }
        return departmentVOS;
    }


    /**
     * 查找所有系主任
     *
     * @return
     */
    @Override
    public List<DeanVO> findDeanList() {
        List<Role> roles = roleMapper.selectList(
                new QueryWrapper<Role>()
                        .eq("id", BizUserTypeEnum.DEAN.getVal()));
        List<DeanVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            Role role = roles.get(0);
            List<UserRole> userRoleList = userRoleMapper.selectList(
                    new QueryWrapper<UserRole>()
                            .eq("role_id",role.getId()));
            if (!CollectionUtils.isEmpty(userRoleList)) {
                //存放所有系主任的id
                List<Long> userIds = new ArrayList<>();
                for (UserRole userRole : userRoleList) {
                    userIds.add(userRole.getUserId());
                }
                if(userIds.size()>0){
                    for (Long userId : userIds) {
                        User user = userMapper.selectById(userId);
                        //所有可用的
                        if(user!=null&&user.getStatus()== UserStatusEnum.AVAILABLE.getStatusCode()){
                            DeanVO deanVO = new DeanVO();
                            deanVO.setName(user.getUsername());
                            deanVO.setId(user.getId());
                            list.add(deanVO);
                        }
                    }
                }
            }
        }
        return list;
    }


    /**
     * 添加部门
     * @param departmentVO
     */
    @Override
    public void addDept(DepartmentVO departmentVO) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentVO,department);
        department.setCreateTime(new Date());
        department.setModifiedTime(new Date());
        departmentMapper.insert(department);
    }


    /**
     * 更新部门
     *
     * @param id
     * @param departmentVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDept(Long id, DepartmentVO departmentVO) throws SystemException {
        Department dbDepartment = departmentMapper.selectById(id);
        if(dbDepartment==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要更新的部门不存在");
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentVO,department);
        department.setId(id);
        department.setModifiedTime(new Date());
        departmentMapper.updateById(department);
    }


}
